<?php

/**
 * This class manages all HTTP requests concerning events.
 * 
 */
class EventController extends Zend_Controller_Action {

    protected $_namespace = 'EventController';
    protected $_session;

    public function init() {
	$this->_session = new Zend_Session_Namespace($this->_namespace);
	$this->_helper->acl->allow('admin')
		->allow('user', array('index', 'list','childeventdetail'));
	$contextSwitch = $this->_helper->getHelper('contextSwitch');
	$contextSwitch->addActionContext('index', 'json')
		->initContext();
    }

    /**
     * Show all events.
     */
    public function indexAction() {
	$session = $this->_session = new Zend_Session_Namespace('redirect');
	if (isset($session->url))
	    unset($session->url);
	$m = new Model_Event;
	if ($this->_request->isXmlHttpRequest()) {
	    //$this->_helper->viewRenderer->setNoRender();
	    //$this->getHelper('layout')->disableLayout();
	    $this->_helper->contextSwitch('json');
	    $startDate = $this->_getParam("startDate");
	    $stopDate = $this->_getParam("endDate");
	    $categories = $this->_getParam("categories");
	    $denied = $this->_getParam("denied");
	    if($denied==null)$denied=false;
	    $sessionDate = new Zend_Date($startDate);
	    $sessionDate->addDay(1);
	    $sessionDate->set('08:00:00', Zend_Date::TIMES);
	    $this->_session->startDate = $sessionDate->toString(Zend_Date::ISO_8601);
	    $events = $m->listEventsBetween($startDate, $stopDate, $categories, $denied);
        
	    $returnVals = array();
	    foreach ($events as $event) {
		if ($event['event_type'] != 'Konferenz' && $event['event_type'] != 'Feste/Veranstaltungen' && $event['event_type'] != 'Sonstiges') {
		    $elp = new Model_EventLinkPerson;
		    if ($elp->findByEvent($event['id'])) {
			$c = new Model_Child;
			$person = $c->find($elp->findByEvent($event['id'])['idperson']);
			if ($person['person_type'] == 'Kind') {
			    $event['description'] = $person['forename'] . ' ' . $person['age'];
			}
		    }
		}
		$returnVals[] = array(
		    'id' => $event['id'],
		    'start' => $event['date_from'],
		    'end' => $event['date_to'],
		    'title' => $event['description'],
		    'category' => $event['event_type'],
		    'status' => $event['event_status'],
		    'series' => $event['idevent_series'],
		    'userId' => 0
		);
	    }
        
            if(is_array($categories)) {
                if(count($categories)) {
                    $category_token = 'Arbeitszeiten';
                    $bWorktime = false;
                    foreach($categories as $k=>$v) {
                        if($v == $category_token) {
                            $bWorktime |= true;
                            break;
                        }
                    }
                    if($bWorktime) {
                        $mw = new Model_Worktime();
                        $worktimes = $mw->getWorktimes($startDate,$stopDate,'wt','all');
                        foreach($worktimes as $wt) {
                            $aPerson = $mw->getWorkerById($wt['idperson']);
                            $sPerson = $aPerson['forename'].' '.$aPerson['surname'];                    
                            $returnVals[] = array(
                                'id' => $wt['id'],
                                'start' => $wt['date_from'],
                                'end' => $wt['date_to'],
                                'title' => '<b>Arbeitszeit<br>'.$sPerson.'<br>'.($wt['idworktime_series']>0 ? "S ".$wt['idworktime_series']:"").'<br>'.'</b>'.$wt['description'],
                                'category' => $category_token,
                                'userId' => 0
                            );
                        }
                    }
                }
            }
        
	    //$jsonData = Zend_Json::encode($returnVals);
	    //$this->response->appendBody($jsonData);
	    $this->_helper->json->sendJson($returnVals);
	} else {
	    $events = $m->listWeek();
	    $this->view->events = $events;
	    //$this->view->eventCount = count($events);
	}
    }

    /**
     * Show childevent details.
     */
    public function childeventdetailAction() {
	$m = new Model_Event;
	if ($this->_request->isXmlHttpRequest()) {
	    //$this->_helper->viewRenderer->setNoRender();
	    //$this->getHelper('layout')->disableLayout();
	    $this->_helper->contextSwitch('json');
	    $eventID = $this->_getParam("eventID");
	    $event = $m->find($eventID);
	    if ($event === false) {
		$this->_helper->json->sendJson(array('status' => 1, 'message' => 'Fehler: Kein Termin gefunden.'));
		return;
	    }
	    if ($event['event_type'] != 'Fester Termin' && $event['event_type'] != 'Einzeltermin' && $event['event_type'] != 'Eingewöhnungstermin') {
		$this->_helper->json->sendJson(array('status' => 2, 'message' => 'Fehler: Kein Betreuungstermin.'));
		return;
	    }
	    $melp = new Model_EventLinkPerson();
	    $childLink = $melp->findByEvent($event['id']);
	    if ($childLink === false) {
		$this->_helper->json->sendJson(array('status' => 3, 'message' => 'Fehler: Keine Zuordnung zu einem Kind vorhanden.'));
		return;
	    }
	    $mchild = new Model_Child();
	    $child = $mchild->find($childLink['idperson']);
	    $mplp = new Model_PersonLinkPerson();
	    $parents = $mplp->findParents($childLink['idperson']);
	    switch (count($parents)) {
		case 0: $parent1 = false;
		    $parent2 = false;
		    break;
		case 1: $parent1 = $parents[0];
		    $parent2 = false;
		    break;
		default : $parent1 = $parents[0];
		    $parent2 = $parents[1];
	    }
	    /*
	     * @TODO: Parents etc...
	     */

	    $this->_helper->json->sendJson(array('status' => 0, 'event' => $event, 'child' => $child, 'parent1' => $parent1, 'parent2' => $parent2, 'message' => 'Daten zu ' . $child['forename'] . ' ' . $child['surname'] . ' wurden geladen'));
	}
    }

    /**
     * Show all events.
     */
    public function listAction() {
	$session = $this->_session = new Zend_Session_Namespace('redirect');
	if (isset($session->url))
	    unset($session->url);
	$m = new Model_Child;
	$events = $m->listAll();
	$this->view->events = $events;
	$this->view->eventCount = count($events);
    }

    /**
     * Create a new event.
     * 
     * Without POST data, an empty form is displayed.
     * With valid POST data, the child is persisted and one gets redirected
     * to the listAction.
     * With invalid POST data, the form's values with error messages is displayed.
     */
    public function createAction() {
	$request = $this->getRequest();
	$form = new Application_Form_Event();
	$form->removeElement('event_status');
	if ($request->getRequestUri() == '/event/create') {
	    $elem=$form->getElement('event_type');
	    $elem->removeMultiOption('Fester Termin');
	    $elem->removeMultiOption('Abgesagter Termin');
	    $elem->removeMultiOption('Eingewöhnungstermin');
	    $elem->removeMultiOption('Einzeltermin');
	    $form->removeElement('child_id');
	}
	// If a child_id is set, it will be preselected
	$childId = $request->getParam('child_id');
	if ($childId != null) {
	    $form->preselectChild($childId);
	}

	if ($request->isPost() && isset($request->getPost()['add_event'])) {
	    if (!$form->isValid($request->getPost())) {
		$this->view->form = $form;
		return;
	    }

	    $startDate = new Zend_Date($request->getPost()['date_from']);
	    $endDate = new Zend_Date($request->getPost()['date_to']);
	    if ($startDate->isEarlier($endDate)) {
		if ($form->isValid($request->getPost())) {
		    $c = $form->getValues();
		    $m = new Model_Event;
		    $m->create($c);

		    return $this->_helper->redirector('index');
		}
	    } else {
		$form->populate($request->getPost());
	    }
	} else {
	    $form_values = $request->getPost();
	    $preDefined['date_from'] = $form_values['date_from'];
	    $preDefined['date_to'] = $form_values['date_to'];
	    $form->populate($preDefined);
	}

	$this->view->form = $form;
    }

    /**
     * Update data of an existing event.
     * 
     * URL parameter id<int> is required.
     * 
     * Without POST data, a form is with the events data is displayed.
     * With valid POST data, the event is persisted and the user is redirected
     * to /event/index.
     * With invalid POST data, the form's values with error messages is displayed.
     */
    public function updateAction() {
	$request = $this->getRequest();
	$id = (int) $request->getParam('id');
	if(!$id)
	    $this->_helper->redirector('index');
	$form = new Application_Form_Event();
	$form->getElement('frequence')
	     ->removeValidator("Fkb_Validate_EventFrequenceNeeded");
	$form->getElement('last_date')
	     ->clearValidators()
	     ->setRequired(false);
	$form->getElement('add_event')
	     ->setLabel('Termin ändern');
	$m = new Model_Event;
	$elp = new Model_EventLinkPerson;
	$personId = $elp->findByEvent($id);
	if ($request->isPost() && isset($request->getPost()['add_event'])) {
	    $startDate = new Zend_Date($request->getPost()['date_from']);
	    $endDate = new Zend_Date($request->getPost()['date_to']);
	    if ($request->getPost()['event_type'] == 'Fester Termin' || $request->getPost()['event_type'] == 'Eingewöhnungstermin' || $request->getPost()['event_type'] == 'Einzeltermin' || $request->getPost()['event_type'] == 'Abgesagter Termin') {
		$form->addInCaretimeValidator();
		$form->getElement('description')
		     ->addValidator(new Fkb_Validate_IsChildEventAcceptable());
	    }
	    if(!isset($request->getPost()['event_status']) || $request->getPost()['event_status']=='Angenommen'){
		$temp_event_status=$request->getPost()['event_status'];
		$form->removeElement('event_status');
		$form->addElement('hidden', 'event_id', array('ignore' => true,'value'=>$request->getPost()['event_id']));
	    }
	    if ($startDate->isEarlier($endDate)) {
		if ($form->isValid($request->getPost())) {
		    $c = $form->getValues();
		    if(isset($temp_event_status))
			$c['event_status']=$temp_event_status;
		    $c['id'] = $id;

		    $m->update($c);

		    // check if a redirect is requested
		    $session = $this->_session = new Zend_Session_Namespace('redirect');
		    if (isset($session->url)) {
			$url = $session->url;
			unset($session->url);
		    } else {
			$url = '/event';
		    }

		    return $this->redirect($url);
		}
	    } else {
		$form->populate($request->getPost());
	    }
	} else {
	    $c = $m->find($id);
	    if ($personId != null) {
		$form->setSelectedPersons($personId['idperson']);
	    }
	    if ($c['idevent_series'] != null)
		$c['frequence'] = 'WEEKLY';
	    else
		$c['frequence'] = 'ONCE';
	    $form->getElement('frequence')
		 ->setValue(array($c['frequence']));
	    $form->removeAllMultioptionsExcept('frequence',$c['frequence']);
	    if ($c['event_type'] == 'Fester Termin' || $c['event_type'] == 'Eingewöhnungstermin' || $c['event_type'] == 'Einzeltermin' || $c['event_type'] == 'Abgesagter Termin') {
		if($c['event_status']=='Angenommen' || $c['event_status']==null)
			$form->removeElement('event_status');
		$form->removeAllMultioptionsExcept('event_type',$c['event_type']);
		$form->removeAllMultioptionsExcept('child_id',$personId['idperson']);
		$form->addElement('hidden', 'event_id', array('ignore' => true,'value'=>$c['id']));
		$form->addElement('hidden', 'series_id', array('ignore' => true,'value'=>$c['idevent_series']));
		
	    } else {
		$form->removeElement('event_status');
		$elem=$form->getElement('event_type');
		$elem->removeMultiOption('Fester Termin');
		$elem->removeMultiOption('Abgesagter Termin');
		$elem->removeMultiOption('Eingewöhnungstermin');
		$elem->removeMultiOption('Einzeltermin');
		$form->removeElement('child_id');
		$form->addElement('hidden', 'event_id', array('ignore' => true,'value'=>$c['id']));
		$form->addElement('hidden', 'series_id', array('ignore' => true,'value'=>$c['idevent_series']));
	    }
	    /*
	     * TODO: fix setCation or setAttrib
	     */
	    if (isset($request->getPost()['date_from']))
		$c['date_from'] = $request->getPost()['date_from'];
	    if (isset($request->getPost()['date_to']))
		$c['date_to'] = $request->getPost()['date_to'];
	    $c['date_from'] = new Zend_Date($c['date_from']);
	    $c['date_from'] = $c['date_from']->toString('dd.MM.yyyy HH:m');
	    $c['date_to'] = new Zend_Date($c['date_to']);
	    $c['date_to'] = $c['date_to']->toString('dd.MM.yyyy HH:m');
	    $form->populate($c);
	    $form->setAction('/event/update/id/' . $id);
	}

	$this->view->form = $form;
    }
    public function updateseriesAction() {
	$request = $this->getRequest();
	$id = (int) $request->getParam('id');
	$series_id = (int) $request->getParam('series_id');
	$form = new Application_Form_Event();
	$form->getElement('frequence')
	     ->removeValidator("Fkb_Validate_EventFrequenceNeeded");
	$form->getElement('last_date')
	     ->clearValidators()
	     ->setRequired(false);
	$form->getElement('add_event')
	     ->setLabel('Termin ändern');
	$m = new Model_Event;
	$elp = new Model_EventLinkPerson;
	$personId = $elp->findByEvent($id);
	if ($request->isPost() && isset($request->getPost()['add_event'])) {
	    $startDate = new Zend_Date($request->getPost()['date_from']);
	    $endDate = new Zend_Date($request->getPost()['date_to']);
	    if ($startDate->isEarlier($endDate)) {
		if ($form->isValid($request->getPost())) {
		    $c = $form->getValues();
		    unset($c['event_id']);
		    $c['id'] = $id;
		    $c['series_id'] = $series_id;
		    $m->updateSeries($c);

		    // check if a redirect is requested
		    $session = $this->_session = new Zend_Session_Namespace('redirect');
		    if (isset($session->url)) {
			$url = $session->url;
			unset($session->url);
		    } else {
			$url = '/event';
		    }

		    return $this->redirect($url);
		}
	    } else {
		$form->populate($request->getPost());
	    }
	} else {
	    $c = $m->find($id);
	    if ($personId != null) {
		$form->setSelectedPersons($personId['idperson']);
	    }
	    $c['frequence'] = 'WEEKLY';
	    $form->getElement('frequence')
		 ->setValue(array($c['frequence']));
	    $form->removeAllMultioptionsExcept('frequence',$c['frequence']);
	    $form->getElement('event_type')
		 ->removeMultiOption('Fester Termin')
		 ->removeMultiOption('Abgesagter Termin')
		 ->removeMultiOption('Eingewöhnungstermin')
		 ->removeMultiOption('Einzeltermin');
	    $form->removeElement('child_id');
	    $form->addElement('hidden', 'event_id', array('ignore' => true,'value'=>$c['id']));
	    $form->addElement('hidden', 'series_id', array('ignore' => true,'value'=>$c['idevent_series']));
	    /*
	     * TODO: fix setCation or setAttrib
	     */
	    if (isset($request->getPost()['date_from']))
		$c['date_from'] = $request->getPost()['date_from'];
	    if (isset($request->getPost()['date_to']))
		$c['date_to'] = $request->getPost()['date_to'];
	    $c['date_from'] = new Zend_Date($c['date_from']);
	    $c['date_from'] = $c['date_from']->toString('dd.MM.yyyy HH:m');
	    $c['date_to'] = new Zend_Date($c['date_to']);
	    $c['date_to'] = $c['date_to']->toString('dd.MM.yyyy HH:m');
	    $form->populate($c);
	    $form->setAction('/event/update/id/' . $id);
	}

	$this->view->form = $form;
    }
    /**
     * Remove an existing event.
     * 
     * URL parameter id<int> is required. The user is redirected to /event/index
     */
    public function deleteAction() {
	$request = $this->getRequest();
	$id = (int) $request->getParam('id');

	$m = new Model_Event;
	$this->_session->eventsAvailable = $m->areEventsBetween($id);
	if($request->getParam('deleteSeries')=="true")
	    $m->deleteSeries($id);
	else
	    $m->delete($id);
	return $this->_helper->redirector('index');
    }

}
